#include "NullSpatialPartitioning.h"

namespace physicsworks {

NullSpatialPartitioning::NullSpatialPartitioning(const vec3& a, const vec3& b) {
	max.x = std::max(a.x, b.x);
	max.y = std::max(a.y, b.y);
	max.z = std::max(a.z, b.z);
	
	min.x = std::min(a.x, b.x);
	min.y = std::min(a.y, b.y);
	min.z = std::min(a.z, b.z);
}

list<pair<RigidBody*,RigidBody*> > NullSpatialPartitioning::getPotentialCollidingPairs() {
		
	list<pair<RigidBody*,RigidBody*> > l;
	
	RigidBodyHSet::const_iterator iter0, iter1;
	for (iter0 = rigidBodies.begin(); iter0 != rigidBodies.end(); ++iter0) {
		
		iter1 = iter0;
		for (++iter1; iter1 != rigidBodies.end(); ++iter1) {
			
			l.push_back(pair<RigidBody*,RigidBody*>(*iter0, *iter1));
		}
	}
	
	return l;
}

void NullSpatialPartitioning::update() {
	RigidBodyHSet newOutRigidBodies;
	
	RigidBodyHSet::iterator iter;
	for (iter = rigidBodies.begin(); iter != rigidBodies.end();) {
		
		if ( !isInsideGridBoundaries((*iter)->getBoundingBox()) ) {
			newOutRigidBodies.insert(*iter);
			rigidBodies.erase(iter++);
		} else
			++iter;
	}
	
	for (iter = outRigidBodies.begin(); iter != outRigidBodies.end();) {
	
		if ( isInsideGridBoundaries((*iter)->getBoundingBox()) ) {
			rigidBodies.insert(*iter);
			outRigidBodies.erase(iter++);
		} else
			++iter;
	}
	
	outRigidBodies.insert(newOutRigidBodies.begin(), newOutRigidBodies.end());
}

}
